<?php

namespace app\common\model;

use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use think\facade\Cache;

class Config extends Base
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';

    // 设置json类型字段
    protected $json = ['value'];

    // 设置JSON数据返回数组
    protected $jsonAssoc = true;

    /**
     * 配置信息
     * @param string $key
     * @param array $value
     * @return mixed
     */
    public static function config(string $key, array $value = [])
    {
        $name  = "config:$key";
        $cache = Cache::store('redis');
        if ($value) {
            $cache->set($name, $value, 7200);
            return self::where('key', $key)->update(['value' => $value]);
        }
        $value = $cache->get($name);
        if (!$value) {
            $value = self::where('key', $key)->value('value');
            $value = $value ?: [];
            $cache->set($name, $value, 7200);
        }
        return $value;
    }

    /**
     * 发送邮件
     */
    public static function mail($to, $subject, $content): array
    {
        $config = self::config('email');

        //Instantiation and passing `true` enables exceptions
        $mail = new PHPMailer(true);

        try {
            //Server settings
            $mail->SMTPDebug = SMTP::DEBUG_OFF;                         //Enable verbose debug output
            $mail->isSMTP();                                            //Send using SMTP
            $mail->Host       = $config['host'];                        //Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = $config['username'];                    //SMTP username
            $mail->Password   = $config['password'];                    //SMTP password
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
            $mail->Port       = $config['port'];                        //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

            if ($mail->Port == '465') {
                $mail->SMTPSecure = 'ssl';
            }

            //Recipients
            $mail->setFrom($config['address'], $config['name']);
            if (is_array($to)) {
                foreach ($to as $v){
                    $mail->addAddress($v);
                }
            } else {
                $mail->addAddress($to);
            }
            //$mail->addAddress('joe@example.net', 'Joe User');     //Add a recipient
            //$mail->addAddress('ellen@example.com');               //Name is optional
            //$mail->addReplyTo('info@example.com', 'Information');
            //$mail->addCC('cc@example.com');
            //$mail->addBCC('bcc@example.com');

            //Attachments
            //$mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
            //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name

            //Content
            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = $subject;
            $mail->Body    = $content;// $mail->msgHTML($content);
            //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

            if (!$mail->send()){
                return ['code' => 1, 'message' => $mail->ErrorInfo];
            }
            return ['code' => 0, 'message' => 'Message has been sent'];
        } catch (Exception $e) {
            return ['code' => 1, 'message' => $e->getMessage()];
        }
    }
}
